import json
import re
import datetime
from django.db.models import Q

from pprint import pprint

from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from finance.models import FinanceOfStore
from finance.serializers import StoreFinanceViewSerializer, OrderForFinanceSerializer
from orders.models import Orders, OrdersMoney, OrderItem
from store.models import StoreManagement, UserAndStore
from users.models import User
from vne_erp.utils import iosformat


def amount_finance(finance_data):
    amount_finance = dict()
    amount_finance["amount_customer_num"] = int()
    amount_finance["amount_order_num"] = int()
    amount_finance["amount_order_amount_money"] = float()
    amount_finance["amount_order_pay_money"] = float()
    amount_finance["amount_order_pay_num"] = int()
    amount_finance["amount_customer_pay_num"] = int()
    amount_finance["amount_order_cancel_num"] = int()
    amount_finance["amount_good_counts"] = int()
    amount_finance["amount_average_customer_money"] = float()
    num = 0
    for day_finance_dict in finance_data.values():
        num += 1
        amount_finance["amount_customer_num"] += day_finance_dict['customer_num']
        amount_finance["amount_order_num"] += day_finance_dict['order_num']
        amount_finance["amount_order_amount_money"] += float(day_finance_dict['order_amount_money'])
        amount_finance["amount_order_pay_money"] += float(day_finance_dict['order_pay_money'])
        amount_finance["amount_order_pay_num"] += day_finance_dict['order_pay_num']
        amount_finance["amount_customer_pay_num"] += day_finance_dict['customer_pay_num']
        amount_finance["amount_order_cancel_num"] += day_finance_dict['order_cancel_num']
        amount_finance["amount_good_counts"] += day_finance_dict['good_counts']
        amount_finance["amount_average_customer_money"] += float(day_finance_dict['average_customer_money'])
    amount_finance["amount_order_amount_money"] = float("%.2f" % amount_finance["amount_order_amount_money"])
    amount_finance["amount_order_pay_money"] = float("%.2f" % amount_finance["amount_order_pay_money"])
    amount_finance["amount_average_customer_money"] = float("%.2f" % (amount_finance["amount_average_customer_money"] / num if num != 0 else 1))
    return amount_finance


def get_store_finance(SalesChannel, StoreName, time_range):
    """获取店铺数据统计"""
    now_time = datetime.datetime.now()

    # seven_time = iosformat.isoformat()
    if isinstance(time_range, list):
        time_range[0] = iosformat.isoformat(datetime.datetime.strptime(time_range[0], '%Y/%m/%d'))
        time_range[1] = iosformat.isoformat(datetime.datetime.strptime(time_range[1], '%Y/%m/%d'))
    elif time_range == '7':
        time_range = iosformat.week_get(now_time)
    elif time_range == '30':
        time_range = iosformat.month_get(now_time)
    elif time_range == "all":
        time_range = iosformat.month_get(now_time)
    elif time_range == '1':
        time_range = iosformat.day_get(now_time)
    else:
        time_range = iosformat.month_get(now_time)

    store_finance = FinanceOfStore.objects.filter(StoreName__in=StoreName)
    store_finance = store_finance.filter(Time__range=(time_range[0],time_range[1]))
    store_finance = store_finance.filter(SalesChannel__in=SalesChannel)

    serializer = StoreFinanceViewSerializer(store_finance, many=True)

    time_set = set()
    # buyer_set = set()
    for i in serializer.data:
        # time = re.match(".{10}", str(i.PurchaseDate)).group()
        time = re.match(".{10}", str(i['Time'])).group()
        time_set.add(time)

    time_list = list(time_set)
    count = len(time_list)
    for n in range(0, count):
        for m in range(n + 1, count):
            if time_list[n] > time_list[m]:
                time_list[n], time_list[m] = time_list[m], time_list[n]

    finance_dict = dict()
    for order_time in time_list:
        finance_list = list()
        for o in serializer.data:
            if re.match(".{10}", str(o['Time'])).group() == order_time:
                finance_list.append(o)
        finance_dict[order_time] = finance_list
    new_finance_dict = dict()
    for h, j in finance_dict.items():
        day_finance_dict = dict()
        num = 0
        money = 0
        k = 0
        c = 0
        goods_counts = 0
        for j_items in j:
            k += 1
            if j_items['OrderStatus'] != 'Canceled':
                goods_counts += j_items['GoodsCounts']
                num += 1
                money += float(j_items['Money'])
            else:
                c += 1
        day_finance_dict['customer_num'] = num
        day_finance_dict['order_num'] = k
        day_finance_dict['order_amount_money'] = "%.2f" % money
        day_finance_dict['order_pay_money'] = "%.2f" % money
        day_finance_dict['order_pay_num'] = num
        day_finance_dict['customer_pay_num'] = num
        day_finance_dict['order_cancel_num'] = c
        day_finance_dict['good_counts'] = goods_counts
        day_finance_dict['average_customer_money'] = "%.2f" % (money / num if num != 0 else 0)
        new_finance_dict[h] = day_finance_dict

    return new_finance_dict


class StoreFinanceView(APIView):
    def get(self, request):
        # 1 获取绩效数据   #更新绩效
        FinanceOfStore.objects.all().delete()
        orders = Orders.objects.all()

        finance_dict = dict()
        serializer_for_orders = OrderForFinanceSerializer(orders, many=True)
        for i in serializer_for_orders.data:
            # print(i)
            # return Response(i)
            finance_dict['Time'] = i.get("PurchaseDate")
            finance_dict['StoreName'] = i['SellerStore']['store']
            finance_dict['BuyerName'] = i['BuyerName'] if i['BuyerName'] else "暂无"
            finance_dict['SalesChannel'] = i['SalesChannel']
            finance_dict['Money'] = i['OrderTotal']['Amount']
            finance_dict['ShippingMoney'] = 0
            finance_dict['TaxMoney'] = 0
            for j in i['orderitem_set']:
                finance_dict['ShippingMoney'] += float(j['ShippingPrice']['Amount'])
                finance_dict['TaxMoney'] += (
                                             float(j['GiftWrapPrice']['Amount']) +
                                             float(j['ItemTax']['Amount']) +
                                             float(j['ShippingTax']['Amount']) +
                                             float(j['GiftWrapTax']['Amount']) +
                                             float(j['ShippingDiscountTax']['Amount']) +
                                             float(j['ShippingDiscount']['Amount']) +
                                             float(j['PromotionDiscountTax']['Amount']) +
                                             float(j['PromotionDiscount']['Amount']) +
                                             float(j['CODFee']['Amount']) +
                                             float(j['CODFeeDiscount']['Amount']))
            finance_dict['ShippingMoney'] = round(finance_dict['ShippingMoney'], 2)
            finance_dict['TaxMoney'] = round(finance_dict['TaxMoney'], 2)
            finance_dict['OrderStatus'] = i['OrderStatus']
            finance_dict['GoodsCounts'] = i['NumberOfItemsShipped']
            finance_dict['FulfillmentChannel'] = i['FulfillmentChannel']
            # print(finance_dict)
            store_finance_serialzier = StoreFinanceViewSerializer(data=finance_dict)
            store_finance_serialzier.is_valid()

            # print(store_finance_serialzier.errors)
            store_finance_serialzier.save()

        return Response({"success_msg": "数据入库成功"})


    def post(self, request):
        """
        根据筛选条件获取店铺绩效
        根据时间范围，销售渠道，销售店铺来确定返回数据
        数据列表 = 时间 - 客户数 - 订单量 - 订单总金额 - 付款金额 - 付款订单数 - 付款客户数- 退款金额 - 退款订单数 - 退款客户数 - 客单价
        """
        # 根据筛选条件返回响应绩效列表
        # time_range = request.POST.get('time_range')
        datas = request.data
        # print(datas)
        time_range = datas.get('time_range')
        SalesChannel = datas.get('SalesChannel')
        StoreName = datas.get('StoreName')
        if isinstance(time_range,list):
            return_time = datetime.datetime.strptime(time_range[1], '%Y/%m/%d') - datetime.datetime.strptime(time_range[0],
                                                                                                         '%Y/%m/%d')
            return_time = str(return_time.days)
        else:
            return_time = time_range
        # print(SalesChannel, StoreName, time_range)
        store_finance_dict = get_store_finance(SalesChannel, StoreName, time_range)
        # print(store_finance_dict)
        # amount_store_finance = amount_finance(store_finance_dict)
        # store_finance_dict['amount_staff_finance'] = amount_store_finance
        store_finance_list = list()
        for time, day_data in store_finance_dict.items():
            day_data['time'] = time
            store_finance_list.append(day_data)

        customer_num = list()
        order_num = list()
        order_amount_money = list()
        order_pay_money = list()
        order_pay_num = list()
        customer_pay_num = list()
        order_cancel_num = list()
        good_counts = list()
        average_customer_money = list()
        # time_list = list()
        for one_data in store_finance_list:
            customer_num.append(one_data.get('customer_num'))
            order_num.append(one_data.get('order_num'))
            order_amount_money.append(float(one_data.get('order_amount_money')) if one_data.get('order_amount_money') else 0)
            order_pay_money.append(float(one_data.get('order_pay_money')) if one_data.get('order_pay_money') else 0)
            order_pay_num.append(one_data.get('order_pay_num'))
            customer_pay_num.append(one_data.get('customer_pay_num'))
            order_cancel_num.append(one_data.get('order_cancel_num'))
            good_counts.append(one_data.get('good_counts'))
            average_customer_money.append(float(one_data.get('average_customer_money')) if one_data.get('average_customer_money') else 0)
            # time_list.append(one_data.get('time'))
        data_lists = {"customer_num_list": customer_num, "order_num_list": order_num,
                      "order_amount_money_list": order_amount_money,
                      "order_pay_money_list": order_pay_money, "order_pay_num_list": order_pay_num,
                      "customer_pay_num_list": customer_pay_num,
                      "order_cancel_num_list": order_cancel_num, "good_counts_list": good_counts,
                      "average_customer_money_list": average_customer_money,
                      }

        sum_list = {
            "customer_num_sum":sum(data_lists['customer_num_list']),
            "order_num_sum":sum(data_lists['order_num_list']),
            "order_amount_money_sum":round(sum(data_lists['order_amount_money_list']),2),
            "order_pay_money_sum":round(sum(data_lists['order_pay_money_list']),2),
            "order_pay_num_sum":sum(data_lists['order_pay_num_list']),
            "customer_pay_num_sum":round(sum(data_lists['customer_pay_num_list']),2),
            "order_cancel_num_sum":sum(data_lists['order_cancel_num_list']),
            "good_counts_sum":sum(data_lists['good_counts_list']),
            "average_customer_money_num":round(sum(data_lists['average_customer_money_list']),2),
                    }

        resp_data = {"staff_finance": store_finance_list, 'time_range': return_time, "data_lists": data_lists,"sum_list":sum_list}



        return Response(resp_data)


# class MyPermission(BasePermission):
#
#     def has_permission(self, request, view):
#         """
#         Return `True` if permission is granted, `False` otherwise.
#         """
#         # print("111",request.user)
#         return True

    # def has_object_permission(self, request, view, obj):
    #     """控制对obj对象的访问权限，此案例决绝所有对对象的访问"""
    #     print("222")
    #     return True


class StaffFinanceView(GenericAPIView):

    # permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取筛选条件下的员工绩效
        user = request.user

        datas = request.data
        # print(datas)
        SalesChannel = datas.get('SalesChannel')
        staff = datas.get('staff')
        time_range = datas.get('time_range')
        if isinstance(time_range,list):
            return_time = datetime.datetime.strptime(time_range[1], '%Y/%m/%d') \
                          - datetime.datetime.strptime(time_range[0],'%Y/%m/%d')
            return_time = str(return_time.days)
        else:
            return_time = time_range

        staff_id_list = list()
        staff_name_list = list()
        staff_dict = dict()
        store_list = list()

        staffs = User.objects.filter(username__in=staff)

        for i in staffs:

            staff_id_list.append(i.id)
            staff_name_list.append(i.username)
            stores = UserAndStore.objects.filter(staff=i.id)
            stores = [i.store for i in stores]
            # stores = StoreManagement.objects.filter(staff=i.id)
            for n in stores:
                store_list.append(n.store)

        staff_dict['id'] = staff_id_list
        staff_dict['staff_name'] = staff_name_list
        staff_dict['staff_stores'] = store_list
        # print(SalesChannel, store_list, time_range)
        staff_finance = get_store_finance(SalesChannel, store_list, time_range)

        """
        staff_dict = { 'staff_id_list':[1,2,3],'staff_name_list':[jack,robot,rose], 'store_list':[需要查询的人的所有店铺] 
        staff_dict = [{'staff_id_list':1],'staff_name':jack, 'store_list':[需要查询的人的所有店铺]},
                    {'staff_id':2,'staff_name': jack, 'store_list':[需要查询的人的所有店铺]}] 
        """
        # 统计总数
        # amount_staff_finance = amount_finance(staff_finance)
        # staff_finance['amount_staff_finance'] = amount_staff_finance
        staff_finance_list = list()
        for time, day_data in staff_finance.items():
            day_data['time'] = time
            staff_finance_list.append(day_data)


        customer_num = list()
        order_num = list()
        order_amount_money = list()
        order_pay_money = list()
        order_pay_num = list()
        customer_pay_num = list()
        order_cancel_num = list()
        good_counts = list()
        average_customer_money = list()
        # time_list = list()
        for one_data in staff_finance_list:
            customer_num.append(one_data.get('customer_num'))
            order_num.append(one_data.get('order_num'))
            order_amount_money.append(float(one_data.get('order_amount_money')) if one_data.get('order_amount_money') else 0)
            order_pay_money.append(float(one_data.get('order_pay_money')) if one_data.get('order_pay_money') else 0)
            order_pay_num.append(one_data.get('order_pay_num'))
            customer_pay_num.append(one_data.get('customer_pay_num'))
            order_cancel_num.append(one_data.get('order_cancel_num'))
            good_counts.append(one_data.get('good_counts'))
            average_customer_money.append(float(one_data.get('average_customer_money')) if one_data.get('average_customer_money') else 0)
            # time_list.append(one_data.get('time'))
        data_lists = {"customer_num_list":customer_num, "order_num_list":order_num, "order_amount_money_list":order_amount_money,
                      "order_pay_money_list":order_pay_money, "order_pay_num_list": order_pay_num, "customer_pay_num_list":customer_pay_num,
                      "order_cancel_num_list":order_cancel_num, "good_counts_list":good_counts, "average_customer_money_list":average_customer_money,
                      }


        # return_time = iosformat.isoformat(datetime.datetime.strptime(time_range[1], '%Y/%m/%d')) - iosformat.isoformat(datetime.datetime.strptime(time_range[0], '%Y/%m/%d'))
        # print(return_time)
        sum_list = {
            "customer_num_sum":sum(data_lists['customer_num_list']),
            "order_num_sum":sum(data_lists['order_num_list']),
            "order_amount_money_sum":round(sum(data_lists['order_amount_money_list']),2),
            "order_pay_money_sum":round(sum(data_lists['order_pay_money_list']),2),
            "order_pay_num_sum":sum(data_lists['order_pay_num_list']),
            "customer_pay_num_sum":round(sum(data_lists['customer_pay_num_list']),2),
            "order_cancel_num_sum":sum(data_lists['order_cancel_num_list']),
            "good_counts_sum":sum(data_lists['good_counts_list']),
            "average_customer_money_num":round(sum(data_lists['average_customer_money_list']),2),
                    }
        resp_data = {"staff_finance": staff_finance_list, 'time_range': return_time, "data_lists": data_lists,'sum_list':sum_list}

        # print(resp_data)
        return Response(resp_data)


class OrderFinanceView(GenericAPIView):

    # permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取筛选条件下的订单绩效
        datas = request.data
        # print(datas)
        SalesChannel = datas.get('SalesChannel')
        StoreName = datas.get('StoreName')
        time_range = datas.get('time_range')
        deliver_method = datas.get('deliver_method')
        # print(datas)
        if isinstance(time_range,list):
            return_time = datetime.datetime.strptime(time_range[1], '%Y/%m/%d') - datetime.datetime.strptime(time_range[0],
                                                                                                         '%Y/%m/%d')
            return_time = str(return_time.days)
        else:
            return_time = time_range

        now_time = datetime.datetime.now()

        # seven_time = iosformat.isoformat()
        if isinstance(time_range, list):
            # print("**")
            time_range[0] = datetime.datetime.strptime(time_range[0], '%Y/%m/%d')
            time_range[1] = datetime.datetime.strptime(time_range[1], '%Y/%m/%d')
        elif time_range == '7':
            time_range = iosformat.week_get(now_time)
        elif time_range == '30':
            time_range = iosformat.month_get(now_time)
        elif time_range == "all":
            time_range = iosformat.month_get(now_time)
        elif time_range == '1':
            time_range = iosformat.day_get(now_time)
        else:
            time_range = iosformat.month_get(now_time)
        # print(SalesChannel,StoreName,time_range,deliver_method)
        finance_of_order = FinanceOfStore.objects.filter(Time__range=(time_range[0], time_range[1]))
        finance_of_order = finance_of_order.filter(StoreName__in=StoreName)
        finance_of_order = finance_of_order.filter(SalesChannel__in=SalesChannel)
        finance_of_order = finance_of_order.filter(FulfillmentChannel__in=deliver_method)
        serializer = StoreFinanceViewSerializer(finance_of_order, many=True)
        time_set = set()

        for i in serializer.data:
            time = re.match(".{10}", str(i['Time'])).group()
            time_set.add(time)

        time_list = list(time_set)
        count = len(time_list)
        for n in range(0, count):
            for m in range(n + 1, count):
                if time_list[n] > time_list[m]:
                    time_list[n], time_list[m] = time_list[m], time_list[n]

        finance_dict = dict()
        for order_time in time_list:
            finance_list = list()
            for o in serializer.data:
                if re.match(".{10}", str(o['Time'])).group() == order_time:
                    finance_list.append(o)
            finance_dict[order_time] = finance_list
        # pprint(finance_dict)
        new_finance_dict = dict()

        for h, j in finance_dict.items():

            day_finance_dict = dict()
            num = 0
            money = 0
            ShippingMoney = 0
            TaxMoney = 0
            k = 0
            c = 0
            goods_counts = 0
            for j_items in j:
                # print(j_items)
                k += 1
                if j_items['OrderStatus'] != 'Canceled':
                    goods_counts += j_items['GoodsCounts']
                    num += 1
                    money += float(j_items['Money'])
                    ShippingMoney += float(j_items['ShippingMoney'])
                    TaxMoney += float(j_items['TaxMoney'])
                else:

                    c += 1

            day_finance_dict['order_num'] = k
            day_finance_dict['order_amount_money'] = float("%.2f" % money)
            day_finance_dict['TaxMoney'] = "%.2f" % TaxMoney
            day_finance_dict['ShippingMoney'] = "%.2f" % ShippingMoney
            day_finance_dict['profit'] = "%.2f" % (float(day_finance_dict['order_amount_money']) - float(day_finance_dict['TaxMoney']) - float(day_finance_dict['ShippingMoney']))
            day_finance_dict['given_order_num'] = c   # 退款单数量  暂时用已取消的订单代替  解析结算报告能获取退款订单
            day_finance_dict['given_order_amount_money'] = "0.00"
            if float(day_finance_dict['order_amount_money']) == 0:
                day_finance_dict['order_amount_money'] = 1
            day_finance_dict['given_order_percent'] = "%.2f" % (float(day_finance_dict['given_order_amount_money']) / float(day_finance_dict['order_amount_money']))
            if float(day_finance_dict['ShippingMoney']) == 0:
                day_finance_dict['ShippingMoney'] = 1
            # if float(day_finance_dict['order_amount_money']) == 0:
            #     day_finance_dict['order_amount_money'] = 20

            day_finance_dict['cost_profit_ratio'] = "%.2f" % (float(day_finance_dict['profit']) / float(day_finance_dict['ShippingMoney']))

            day_finance_dict['sales_profit_margin'] = "%.2f" % (float(day_finance_dict['profit']) / float(day_finance_dict['order_amount_money']))

            new_finance_dict[h] = day_finance_dict
        order_finance_list = list()
        for time, day_data in new_finance_dict.items():
            day_data['time'] = time
            order_finance_list.append(day_data)
        # order_finance_list.sort(key=lambda z: z['order_amount_money'], reverse=True)
        order_num = list()
        order_amount_money = list()
        TaxMoney = list()
        ShippingMoney = list()
        profit = list()
        given_order_num = list()
        given_order_amount_money = list()
        given_order_percent = list()
        cost_profit_ratio = list()
        sales_profit_margin = list()
        time = list()
        for one_data in order_finance_list:
            order_num.append(one_data.get('order_num'))
            order_amount_money.append(float(one_data.get('order_amount_money')) if one_data.get('order_amount_money') else 0)
            TaxMoney.append(float(one_data.get('TaxMoney')) if one_data.get('TaxMoney') else 0)
            ShippingMoney.append(float(one_data.get('ShippingMoney')) if one_data.get('ShippingMoney') else 0)
            profit.append(float(one_data.get('profit')) if one_data.get('profit') else 0)
            given_order_num.append(one_data.get('given_order_num'))
            given_order_amount_money.append(float(one_data.get('given_order_amount_money')) if one_data.get('given_order_amount_money') else 0)
            given_order_percent.append(float(one_data.get('given_order_percent')) if one_data.get('given_order_percent') else 0)
            cost_profit_ratio.append(float(one_data.get('cost_profit_ratio')) if one_data.get('cost_profit_ratio') else 0)
            sales_profit_margin.append(float(one_data.get('sales_profit_margin')) if one_data.get('sales_profit_margin') else 0)
            time.append(one_data.get('time'))
        data_lists = {"order_num_list": order_num, "order_amount_money_list": order_amount_money,
                      "TaxMoney_list": TaxMoney,
                      "ShippingMoney_list": ShippingMoney, "profit_list": profit,
                      "given_order_num_list": given_order_num,
                      "given_order_amount_money_list": given_order_amount_money,
                      "given_order_percent_list": given_order_percent,
                      "cost_profit_ratio_list": cost_profit_ratio,
                      "sales_profit_margin_list": sales_profit_margin,
                      "time_list": time,
                      }
        sum_list = {
            "order_num_list":sum(data_lists['order_num_list']),
            "order_amount_money_list":sum(data_lists['order_amount_money_list']),
            "TaxMoney_list":round(sum(data_lists['TaxMoney_list']),2),
            "ShippingMoney_list":round(sum(data_lists['ShippingMoney_list']),2),
            "profit_list":round(sum(data_lists['profit_list']),2),
            "given_order_num_list":sum(data_lists['given_order_num_list']),
            "given_order_amount_money_list":round(sum(data_lists['given_order_amount_money_list']),2),
            "given_order_percent_list":round(sum(data_lists['given_order_percent_list'])/int(return_time),2),
            "cost_profit_ratio_list":round(sum(data_lists['cost_profit_ratio_list'])/int(return_time),2),
            "sales_profit_margin_list":round(sum(data_lists['sales_profit_margin_list'])/int(return_time),2),
                    }

        resp_data = {"staff_finance": order_finance_list, 'time_range': return_time, "data_lists": data_lists,'sum_list':sum_list}


        return Response(resp_data)

class StaffFinanceCompetition(APIView):
    def get(self, request):
        """
        员工绩效比拼：
        查询staff 列表 遍历
        以每一个staff 取出其店铺列表
        将店铺列表传入函数 get_store_finance 获得每日绩效
        将每日绩效传入函数 amount_finance 获得该员工当月总绩效
        将每个员工绩效以销售额进行排名  从而获得员工绩效比拼数据

        """
        time_range = request.GET.get("time_range")
        # print(time_range)
        SalesChannel = ['Amazon.com', 'Amazon.ca', 'Amazon.com.mx']
        staffs = User.objects.all()
        staff_finance_compitition_list = list()

        for i in staffs:
            store_list = list()
            stores = UserAndStore.objects.filter(staff=i.id)
            stores = [i.store for i in stores]
            for n in stores:
                store_list.append(n.store)
            staff_finance = get_store_finance(SalesChannel, store_list, time_range)
            amount_staff_finance = amount_finance(staff_finance)
            amount_staff_finance['staff_name'] = i.username
            staff_finance_compitition_list.append(amount_staff_finance)

        staff_finance_compitition_list.sort(key=lambda z: z['amount_order_amount_money'], reverse=True)
        # staff_finance_compitition_list.reverse()
        staff_finance_compitition_list = staff_finance_compitition_list[:10]

        return Response({"success_msg": staff_finance_compitition_list})


class StoreFinanceCompetition(APIView):
    def get(self, request):
        """
        店铺绩效比拼：
        查询店铺列表 遍历
        将每一个店铺 都传入函数 get_store_finance 获得店铺每日绩效
        将店铺每日绩效传入函数  amount_finance 获得该店铺总绩效
        将每个店铺绩效以销售额进行排名   从而获得店铺绩效比拼数据
        """
        time_range = '30'
        SalesChannel = ['Amazon.com', 'Amazon.ca', 'Amazon.com.mx']
        stores = StoreManagement.objects.all()
        store_finance_compitition_list = list()
        for n in stores:
            store_list = list()
            # store_str = store_str + n.store + ','
            store_list.append(n.store)
            store_finance = get_store_finance(SalesChannel, store_list, time_range)
            # print(store_finance)
            amount_staff_finance = amount_finance(store_finance)
            amount_staff_finance['store_name'] = n.store
            store_finance_compitition_list.append(amount_staff_finance)
        # print(type(store_finance_compitition_list[1]['amount_order_amount_money']))
        store_finance_compitition_list.sort(key=lambda z: z['amount_order_amount_money'])
        store_finance_compitition_list.reverse()
        store_finance_compitition_list = store_finance_compitition_list[:10]
        return Response({"success_msg": store_finance_compitition_list})




